package com.pansoft.openplanet.activity;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.InputFilter;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.appcompat.app.AlertDialog;

import com.efounder.chat.http.JFCommonRequestManager;
import com.efounder.common.BaseRequestManager;
import com.efounder.util.EnvSupportManager;
import com.efounder.utils.NumberTextWatcher;
import com.efounder.utils.ResStringUtil;
import com.pansoft.openplanet.R;
import com.pansoft.openplanet.bean.Account;
import com.pansoft.openplanet.bean.AssetListBean;
import com.pansoft.openplanet.bean.WalletBean;
import com.pansoft.openplanet.constant.IPAssetsConstant;
import com.pansoft.openplanet.db.AccountDao;
import com.pansoft.openplanet.fragment.BottomTransferConfirmDialogFragment;
import com.pansoft.openplanet.fragment.BottomWalletChooseDialogFragment;
import com.pansoft.openplanet.util.BalanceUtil;
import com.pansoft.openplanet.util.BtcNetParamUtil;
import com.pansoft.openplanet.util.BtcTransactionManager;
import com.pansoft.openplanet.util.ChainParamsUtil;
import com.pansoft.openplanet.util.DecimalDigitsInputFilter;
import com.pansoft.openplanet.util.EosNetParamUtil;
import com.pansoft.openplanet.util.TCRequestUtil;
import com.pansoft.openplanet.util.UTXOTransactionManager;
import com.pansoft.openplanet.widget.BlockChainFeeSeekBar;
import com.utilcode.util.StringUtils;
import com.utilcode.util.ToastUtils;

import org.bitcoinj.core.Coin;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import static android.app.DialogFragment.STYLE_NO_FRAME;
import static com.pansoft.openplanet.util.BtcNetParamUtil.URL_BTC_GET_RECOMMENDBTC_FEES;
import static com.pansoft.openplanet.util.BtcNetParamUtil.URL_BTC_GET_UTXO;

public class NewTransferActivity extends TCBaseActivity implements View.OnClickListener, BtcTransactionManager.OnSyncListener {

    public static final String TAG = "NewTransferActivity";
    private TextView tvWallet;
    //付款地址
    private TextView tvPay;
    //备注
    EditText etNote;
    //金额
    EditText etAmount;
    //余额
    TextView tvBalance;
    //收款地址
    EditText etReceive;
    LinearLayout llBalance;
    //代币单位
    TextView tvCoinType;
    LinearLayout llInput;
    LinearLayout llRemark;
    LinearLayout llReceive;
    LinearLayout llPay;
    LinearLayout llAddress;
    ImageView ivChooseWallet;
    TextView tvNext;
    TextView tvTitle;

    private BlockChainFeeSeekBar blockFeeSekbar;


//    //原先的矿工费选择
//    ImageView ivMinerFeeChoose;
//    LinearLayout llExpense;
//    TextView tvExpense;
//    private SeekBar seekBar;
//    private TextView tvMinGas;
//    private TextView tvMaxGas;
//    private LinearLayout llSeekbar;
//    //原先的矿工费选择

    private LinearLayout llAccountContainer;//eos账户选择
    private LinearLayout llAccount;
    private TextView tvAccount;

    public static final int COMMEN_TRANSFER = 1;//普通转账
    public static final int TOKEN_TRANSFER = 2; //代币转账
    public static final int QRCODE_TRANSFER = 3; //扫码普通转账
    public static final int QRCODE_TOKEN_TRANSFER = 4; //扫码代币转账

    //转账模式
    private int transferMode = COMMEN_TRANSFER;
    //钱包货币余额
    private String balance = "0";
    //代币余额
    private String assetBalance = "0";
    //代币单位
    private String assetUnit;
    private AssetListBean assetListBean;
    //当前钱包名
    private String curWalletName;
    //当前地址
    private String curAddress;
    //    //默认手续费
//    private String gas = "0.0008";
    //默认链
    private int ipaChainId = IPAssetsConstant.CHAIN_ID_ETH;

    private List<WalletBean> walletBeans = new ArrayList<>();
    private BtcTransactionManager btcTransactionManager;

    private AccountDao accountDao;
    private Account curAccount;
    private String[] items;

    /**用于预估手续费的输入值, 默认1输入 */
    private int btcInputsSize = 1;

    //是否支持hd钱包
    boolean isHdWallet;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.new_activity_transfer);
        setSwipeBackEnable(false);
        ipaChainId = getIntent().getIntExtra("mode", IPAssetsConstant.CHAIN_ID_ETH);
        accountDao = new AccountDao(this);
        initView();
        initIntentData();

       /* if (ipaChainId == IPAssetsConstant.CHAIN_ID_ETH) {
            initLocalWalletData(IPAssetsConstant.ChainEnum.ETH);
        }
        if (ipaChainId == IPAssetsConstant.CHAIN_ID_ETE) {
            initLocalWalletData(IPAssetsConstant.ChainEnum.ETE);
        } else if (ipaChainId == IPAssetsConstant.CHAIN_ID_BTC) {
            initLocalWalletData(IPAssetsConstant.ChainEnum.BTC);
        } else if (ipaChainId == EosNetParamUtil.getEosChainId()) {
            initLocalWalletData(EosNetParamUtil.getEosChainEnum());
        } else if (ipaChainId == IPAssetsConstant.CHAIN_ID_BCH) {
            initLocalWalletData(IPAssetsConstant.ChainEnum.BCH);
        }*/
        initLocalWalletData(IPAssetsConstant.ChainEnum.getChainEnumByChainId(ipaChainId));


        EventBus.getDefault().register(this);


    }

    /**
     * @param walletName    账户名
     * @param mode          mode ETH， BTC等
     * @param address       账户地址
     * @param balance       账户余额
     * @param assetListBean assetListBean 为null 表示普通转账
     * @param accountType   钱包类型，0是子钱包，1是观察钱包，2是冷钱包
     */
    public static void start(Context context, String walletName, int mode, String address,
                             String balance, AssetListBean assetListBean, int accountType) {
        Intent starter = new Intent(context, NewTransferActivity.class);
        starter.putExtra("walletName", walletName);
        starter.putExtra("mode", mode);
        starter.putExtra("address", address);
        starter.putExtra("balance", balance);
        starter.putExtra("assetBean", assetListBean);
        starter.putExtra("accountType", accountType);
        context.startActivity(starter);
    }


    private void initView() {

        llBalance = (LinearLayout) findViewById(R.id.ll_balance);
        tvCoinType = (TextView) findViewById(R.id.tv_coin_type);
        tvBalance = (TextView) findViewById(R.id.tv_balance);

        llInput = (LinearLayout) findViewById(R.id.ll_input);
        etAmount = (EditText) findViewById(R.id.et_amount);
        llRemark = (LinearLayout) findViewById(R.id.ll_remark);
        etNote = (EditText) findViewById(R.id.et_note);
        llReceive = (LinearLayout) findViewById(R.id.ll_receive);
        etReceive = (EditText) findViewById(R.id.et_receive);
        llPay = (LinearLayout) findViewById(R.id.ll_pay);
        llAddress = (LinearLayout) findViewById(R.id.ll_address);
        llAddress.setOnClickListener(this);
        tvWallet = (TextView) findViewById(R.id.tv_wallet);
        ivChooseWallet = (ImageView) findViewById(R.id.iv_choose_wallet);
        //付款地址
        tvPay = (TextView) findViewById(R.id.tv_pay);

//        llSeekbar = (LinearLayout) findViewById(R.id.ll_seekbar);
//        llSeekbar.setVisibility(View.INVISIBLE);
//        seekBar = (SeekBar) findViewById(R.id.seekBar);
//        tvMinGas = (TextView) findViewById(R.id.tv_min);
//        tvMaxGas = (TextView) findViewById(R.id.miner_value);
//        llExpense = (LinearLayout) findViewById(R.id.ll_expense);
//        tvExpense = (TextView) findViewById(R.id.tv_expense);
//        tvExpense.setOnClickListener(this);
//        ivMinerFeeChoose = (ImageView) findViewById(R.id.iv_miner_fee_choose);
//        ivMinerFeeChoose.setOnClickListener(this);


        tvNext = (TextView) findViewById(R.id.tv_next);
        tvNext.setOnClickListener(this);
        tvTitle = (TextView) findViewById(R.id.tv_title);
        llAccountContainer = (LinearLayout) findViewById(R.id.ll_account_container);
        llAccount = (LinearLayout) findViewById(R.id.ll_account);
        llAccount.setOnClickListener(this);
        tvAccount = (TextView) findViewById(R.id.tv_account);

        blockFeeSekbar = (BlockChainFeeSeekBar) findViewById(R.id.block_fee_sekbar);

        //btc或者eos，隐藏交易费
        if (ipaChainId == EosNetParamUtil.getEosChainId()) {
            blockFeeSekbar.setVisibility(View.INVISIBLE);
        }


        if (ipaChainId == EosNetParamUtil.getEosChainId()) {
            tvPay.setVisibility(View.GONE);
            llAccountContainer.setVisibility(View.VISIBLE);
        }

        initSeekBar();
        etAmount.addTextChangedListener(new NumberTextWatcher(etAmount));
    }

    /**
     * 初始化传递过来的数据
     */
    private void initIntentData() {
        balance = getIntent().getStringExtra("balance") == null ? "0" : getIntent().getStringExtra("balance");
        if (balance != null) {
            balance = balance.replace("BTC", "");
        }
        curWalletName = getIntent().getStringExtra("walletName");
        curAddress = getIntent().getStringExtra("address");
        if (curAddress == null) curAddress = "";
        curAccount = accountDao.getAccount(curAddress);
        //有这个表示代币转账
        assetListBean = (AssetListBean) getIntent().getSerializableExtra("assetBean");

        //这个表示扫码转账
        String tokenTrade = getIntent().getStringExtra("tokenTrade");

        if (ipaChainId == EosNetParamUtil.getEosChainId()) {
            etAmount.setFilters(new InputFilter[]{new DecimalDigitsInputFilter(4)});
        } else {
            etAmount.setFilters(new InputFilter[]{new DecimalDigitsInputFilter(8)});
        }
        //初始化默认标题
        tvTitle.setText(R.string.open_planet_transfer);

        if (assetListBean != null) {
            transferMode = TOKEN_TRANSFER;
            parseTokenData();
        } else if (!StringUtils.isEmpty(tokenTrade)) {
            parseQrCodeData(tokenTrade);
        } else {
            transferMode = COMMEN_TRANSFER;
            parseCommonData();
        }

        isHdWallet = EnvSupportManager.isSupportHDWallet() && !StringUtils.isEmpty(curAccount.getHdBtcCurrentChildAddress());


        if(ipaChainId == IPAssetsConstant.CHAIN_ID_BTC){
            if(isHdWallet){
                //btc交易大小
                getBtcInputSize(isHdWallet);
                //获取推荐手续费
                getBtcRecommendFee();
            }else {
                blockFeeSekbar.setVisibility(View.INVISIBLE);

            }
        }
    }

    /**
     * 解析普通转账数据（eth转账）
     */
    private void parseCommonData() {
        /*if (ipaChainId == IPAssetsConstant.CHAIN_ID_ETH) {
            assetUnit = "ETH";
        } else if (ipaChainId == IPAssetsConstant.CHAIN_ID_ETE) {
            assetUnit = "ETE";
            tvExpense.setText(gas + " ETE");
        } else if (ipaChainId == IPAssetsConstant.CHAIN_ID_BTC) {
            assetUnit = "BTC";
            tvExpense.setText(gas + " feePerKb");
        } else if (ipaChainId == EosNetParamUtil.getEosChainId()) {
            assetUnit = "EOS";
            tvExpense.setText(gas + " eos");
        } else if (ipaChainId == IPAssetsConstant.CHAIN_ID_BCH) {
            assetUnit = "BCH";
        }*/
        assetUnit = ChainParamsUtil.getAssetUnitByChainId(ipaChainId);
        tvBalance.setText(getString(R.string.open_planet_balance_with_unit, balance, assetUnit));
        setViewData();
    }

    /**
     * 解析代币转账数据
     */
    private void parseTokenData() {

        assetUnit = assetListBean.getName();
        assetBalance = assetListBean.getBalance();
        try {
            assetBalance = BalanceUtil.formatPrice(Double.valueOf(assetBalance), true, 8);
        } catch (NumberFormatException e) {
            e.printStackTrace();
            assetBalance = assetListBean.getBalance();
        }
        tvBalance.setText(getString(R.string.open_planet_balance_with_unit, assetBalance, assetUnit));
        setViewData();
    }

    /**
     * 解析扫描转账数据
     */
    private void parseQrCodeData(String tokenTrade) {
        try {
            JSONObject jsonObject = new JSONObject(tokenTrade);
            //收款人
            String receiveAddress = jsonObject.getString("walletAddress");
            etReceive.setText(receiveAddress);
            //是否是 代币转账
            boolean isTokenAcount = jsonObject.getBoolean("isTokenAccount");
            //转账金额
            etAmount.setText(jsonObject.getString("amount"));
            //合约地址
            String contractAddress = jsonObject.getString("contractAddress");

            String chainId = jsonObject.optString("chainId", "2");
            // 钱包单位名称
            assetUnit = jsonObject.optString("tokenUnit", "");
            try {
                ipaChainId = Integer.valueOf(chainId);
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }

            initView();
            //默认使用currentshow 钱包转账
            curAccount = new AccountDao(this).getCurrentShowAccount(ipaChainId);

            if (curAccount != null) {
                curWalletName = curAccount.getAcccountName();
                curAddress = curAccount.getAddress();
                if (isTokenAcount) {
//                    String chainId = jsonObject.getString("chainId");
                    String tokenId = jsonObject.getString("tokenId");
                    initTokenData(curAddress, chainId, tokenId);
                } else {
                    //二维码非代币转账(分为 eth非代币 btc 或者eos)
                    if (ipaChainId == IPAssetsConstant.CHAIN_ID_ETH) {
                        initTokenData(curAddress, chainId, "");
                    } else if (ipaChainId == IPAssetsConstant.CHAIN_ID_ETE) {
                        initTokenData(curAddress, chainId, "");
                    } else if (ipaChainId == IPAssetsConstant.CHAIN_ID_BTC) {
                        parseCommonData();
//                        syncBtcAccount(account.getAddress(), account.getFileName());
                        UTXOTransactionManager.getBalance(TAG, curAccount);
                    } else if (ipaChainId == EosNetParamUtil.getEosChainId()) {
                        setViewData();
                    }

                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    //同步btc 钱包
    private void syncBtcAccount(String address, String fileName) {
        showLoading(ResStringUtil.getString(R.string.open_planet_syncing));
        btcTransactionManager = BtcTransactionManager.getInstance(address, fileName);
        btcTransactionManager.removeOnSyncListener(this);
        btcTransactionManager.addOnSyncListener(this);
        btcTransactionManager.startSync();
    }

    //btc同步回调
    @Override
    public void onSyncProgress(int progress, String currentBtcAddress) {

    }

    @Override
    public void onSyncCompleted(String currentBtcAddress) {
        if (this.isDestroyed()) {
            return;
        }
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                dismissLoading();
            }
        });
    }

    /**
     * 同步后更新余额
     *
     * @param coinBalance
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onBalanceUpdated(Coin coinBalance) {
        balance = coinBalance.toFriendlyString().replace("BTC", "");
        setViewData();
    }

    /**
     * 初始化代币数据
     *
     * @param curAddress
     * @param chainId
     */
    private void initTokenData(final String curAddress, final String chainId, final String tokenId) {
        final HashMap<String, String> map = new HashMap<>();

        boolean isShowTokenBalance = true;
        map.put("chainID", chainId);

        if (!"".equals(tokenId)) {
            map.put("tokenID", tokenId);
            isShowTokenBalance = false;
        } else {
            //todo 故意写一个错误的字段名
            map.put("tokenId", "3");
        }

        map.put("userAddress", curAddress);

        final boolean finalIsShowTokenBalance = isShowTokenBalance;
        TCRequestUtil.getCommonRequest(TAG, "chain/getTokenInfo", map,
                new TCRequestUtil.TCRequestCallback() {
                    @Override
                    public void onSuccess(String response) {
                        dismissLoading();

                        Log.i(TAG, response + "");
                        net.sf.json.JSONObject jsonObject = net.sf.json.JSONObject.fromObject(response);
                        //{"result":"success","AddressBalance":"0","TokenInfo":{"balance":"0","blockChainID":"2",
                        // "tokenAddress":"0xcb97e65f07da24d46bcdd078ebebd7c6e6e3d750","tokenDecimals":8,"tokenFullName":"Bytom",
                        // "tokenID":"10","tokenIcon":"http://cdn.openserver.cn/images/eth/tokens/btm.png","tokenName":"BTM"}}
                        if (jsonObject.getString("result").equals("success")) {
                            if (!tokenId.equals("") && !tokenId.equals("")) {
                                if (jsonObject.containsKey("TokenInfo")) {
                                    net.sf.json.JSONObject tokenInfoObject = jsonObject.getJSONObject("TokenInfo");
                                    assetUnit = tokenInfoObject.optString("tokenName");
                                    String assetBalance = tokenInfoObject.optString("balance", "0");
                                    tvBalance.setText(getString(R.string.open_planet_balance_with_unit, assetBalance, assetUnit));

                                    assetListBean = new AssetListBean.Builder().address(tokenInfoObject.optString("tokenAddress"))
                                            .balance(assetBalance)
                                            .id(tokenInfoObject.optString("tokenID"))
                                            .blockChainID(tokenInfoObject.optString("blockChainID"))
                                            .name(tokenInfoObject.optString("tokenName"))
                                            .icon(tokenInfoObject.optString("tokenIcon"))
                                            .tokenDecimals(tokenInfoObject.optInt("tokenDecimals"))
                                            .build();
                                    setViewData();
                                }
                            } else {

                                balance = jsonObject.getString("AddressBalance");
                                if (!"0".equals(balance) && !"".equals(balance)) {
                                    balance = BalanceUtil.formatPrice(Double.valueOf(balance), true, 8);
                                }
                                tvBalance.setText(getString(R.string.open_planet_balance_with_unit, balance, assetUnit));
//                                mode = IPAssetsConstant.CHAIN_ID_ETH;
                            }
                            parseCommonData();

                        } else {
                            parseCommonData();
                        }
                    }

                    @Override
                    public void onFail(String error) {
                        dismissLoading();
                        setViewData();

                    }
                });

    }

    //设置部分view 的数据
    private void setViewData() {
        tvCoinType.setText(assetUnit);
        tvWallet.setText(curWalletName);
        tvBalance.setText(getString(R.string.open_planet_balance_with_unit, balance, assetUnit));
        tvPay.setText(curAddress);
        tvAccount.setText(curAddress);
        tvTitle.setText(assetUnit + " " + ResStringUtil.getString(R.string.open_planet_transfer));
    }

    /**
     * 初始化seekbar，用于计算转账矿工费用
     */
//    private void initSeekBar() {
//        //btc的，1000到10000 feePerKb
//        if (ipaChainId == IPAssetsConstant.CHAIN_ID_BTC) {
//            //修改默认数值
//            gas = "3000";
//            tvExpense.setText(gas);
//            tvMinGas.setText("1000");
//            tvMaxGas.setText("10000");
//            seekBar.setMax(9000);
//            seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
//                @Override
//                public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
//                    gas = String.valueOf(progress + 1000);
//                    tvExpense.setText(gas + " feePerKb");
//                }
//
//                @Override
//                public void onStartTrackingTouch(SeekBar seekBar) {
//
//                }
//
//                @Override
//                public void onStopTrackingTouch(SeekBar seekBar) {
//
//                }
//            });
//        } else {
//            //最小0.0008，最大0.006
//            seekBar.setMax(52);
//            seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
//                @Override
//                public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
//                    gas = BalanceUtil.formatPrice(new BigDecimal((double) (progress + 8) / 10000)
//                            .doubleValue(), true, 4);
//                    //更新矿工费金额
//                    if (ipaChainId == IPAssetsConstant.CHAIN_ID_ETH) {
//                        tvExpense.setText(gas + " ether");
//                    } else if (ipaChainId == EosNetParamUtil.getEosChainId()) {
//                        tvExpense.setText(gas + " eos");
//                    } else if (ipaChainId == IPAssetsConstant.CHAIN_ID_ETE) {
//                        tvExpense.setText(gas + " ETE");
//                    }
//                }
//
//                @Override
//                public void onStartTrackingTouch(SeekBar seekBar) {
//
//                }
//
//                @Override
//                public void onStopTrackingTouch(SeekBar seekBar) {
//
//                }
//            });
//        }
//    }
    private void initSeekBar() {
        blockFeeSekbar.setChainId(ipaChainId);
    }


    private void getBtcInputSize(boolean isHdWallet){

        HashMap<String, String> map = new HashMap<>();

        if (isHdWallet) {
            String xpub = curAccount.getHdBtcXpub();
            map.put("xpub", xpub);
        }
        else {
            map.put("BtcAddress", curAddress);
        }
        map.put("type", BtcNetParamUtil.NET_TYPE);
        JFCommonRequestManager.getInstance().requestGetByAsyn(TAG, URL_BTC_GET_UTXO, map, new BaseRequestManager.ReqCodeCallBack<String>() {
            @Override
            public void onReqFailed(int errorCode, String errorMsg) {
            }

            @Override
            public void onReqSuccess(String result) {
                try {
                    JSONObject jsonObject1 = new JSONObject(result);
                    if (jsonObject1.optString("result").equals("success")) {
                        JSONArray jsonArray = jsonObject1.optJSONArray("data");
                        btcInputsSize = jsonArray.length();
                        int txSize = BtcNetParamUtil.computeBtcTxSize(btcInputsSize, 2);
                        blockFeeSekbar.setBtcTxSize(txSize);

                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onReqFailed(String errorMsg) {
            }
        });
    }

    /**
     * 请求btc推荐手续费
     */
    private void getBtcRecommendFee() {
        //btc/getRecommendBtcFees

        JFCommonRequestManager.getInstance().requestGetByAsyn(TAG, URL_BTC_GET_RECOMMENDBTC_FEES, new HashMap<String, String>(), new BaseRequestManager.ReqCodeCallBack<String>() {
            @Override
            public void onReqFailed(int errorCode, String errorMsg) {

            }

            @Override
            public void onReqSuccess(String result) {
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    JSONObject msgObject = jsonObject.getJSONObject("msg");
                    int fees = msgObject.optInt("fastestFee");
//                            LogUtils.e("fees---->"+fees);
                    if(fees>0){
                        blockFeeSekbar.setTvRecommendGas(fees);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onReqFailed(String errorMsg) {

            }
        });
    }

    /**
     * 初始化本地钱包数据，根据intent里的类型，决定是哪一类账户
     *
     * @param blockChainEnum ETH，BTC等
     */
    private void initLocalWalletData(IPAssetsConstant.ChainEnum blockChainEnum) {
        List<Account> accountList;
        if (ipaChainId == EosNetParamUtil.getEosChainId()) {
            accountList = accountDao.getAllActivatedEosAccount(blockChainEnum);
        } else {
            accountList = accountDao.getAllChildAccount(blockChainEnum);
        }
        if (accountList != null) {
            for (int i = 0; i < accountList.size(); i++) {
                Account account = accountList.get(i);
                if (account.getAccountType() == Account.ACCOUNT_TYPE_OBSERVE) {
                    //观察钱包不能转账
                    continue;
                }
                WalletBean walletBean = new WalletBean.Builder()
                        .accountName(account.getAcccountName())
                        .avatar(account.getAccountAvatar())
                        .address(account.getAddress())
                        .balance("0")
                        .build();
                if (curAddress.equalsIgnoreCase(walletBean.getAddress())) {
                    walletBean.setSelected(true);
                    walletBean.setBalance(balance);
                }
                walletBeans.add(walletBean);
            }
        }
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (view.getId() == R.id.tv_next) {
            //下一步
            String inputAmount = etAmount.getText().toString().trim();
            if (TextUtils.isEmpty(inputAmount)) {
                ToastUtils.showShort(R.string.open_planet_input_transfer_amount);
                return;
            }
            if (etReceive.getText().toString().equals("")) {
                ToastUtils.showShort(R.string.open_planet_receive_address_not_null);
                return;
            }
            if (tvPay.getText().toString().equals("")) {
                ToastUtils.showShort(R.string.open_planet_select_pay_address);
                return;
            }

            showTransferConfirm();

        } else if (view.getId() == R.id.tv_expense || id == R.id.iv_miner_fee_choose) {
            //选择矿工费用
//            llSeekbar.setVisibility((llSeekbar.getVisibility() == View.VISIBLE ? View.GONE : View.VISIBLE));
        } else if (view.getId() == R.id.ll_address) {
            //选择钱包
            showWalletChoose();
        } else if (view.getId() == R.id.ll_account) {
            //选择Eos钱包账户
            changeAccountAlert();
        }
    }

    /**
     * 切换钱包
     */
    private void showWalletChoose() {

        BottomWalletChooseDialogFragment bottomWalletChooseDialogFragment = new
                BottomWalletChooseDialogFragment();
        bottomWalletChooseDialogFragment.setData(this, walletBeans, ipaChainId);
        bottomWalletChooseDialogFragment.setStyle(STYLE_NO_FRAME, 0);
        bottomWalletChooseDialogFragment.show(getSupportFragmentManager(), "WalletChoose");
        bottomWalletChooseDialogFragment.setOnWalletSelectChangedListener(new BottomWalletChooseDialogFragment.OnWalletSelectChangedListener() {
            @Override
            public void onWalletChanged(WalletBean walletBean) {
                curAddress = walletBean.getAddress();
                curAccount = accountDao.getAccount(curAddress);
                curWalletName = walletBean.getAccountName();
                tvWallet.setText(walletBean.getAccountName());
                tvPay.setText(walletBean.getAddress());
                if (ipaChainId == IPAssetsConstant.CHAIN_ID_BTC) {
                    UTXOTransactionManager.getBalance(TAG, curAccount);
//                    Account btcAccount = new AccountDao(NewTransferActivity.this).getAccount(curAddress);
//                    if (btcAccount != null) {
//                        syncBtcAccount(curAddress, btcAccount.getFileName());
//                    }
                } else if (ipaChainId == EosNetParamUtil.getEosChainId()) {
                    tvAccount.setText(curAddress);
                } else {
                    initTokenData(curAddress, ipaChainId + "", "");
                }

            }
        });
    }

    /**
     * 选择账户
     */
    private void changeAccountAlert() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        int checkedItem = 0;
        if (curAccount.getEosAccountNames() == null || curAccount.getEosAccountNames().equals("")) {
            items = new String[]{curAccount.getAddress()};
        } else {
            items = curAccount.getEosAccountNames().split("_");

            for (int i = 0; i < items.length; i++) {
                if (curAccount.getAddress().equals(items[i])) {
                    checkedItem = i;
                }
            }
        }

        builder.setTitle(ResStringUtil.getString(R.string.open_planet_choose_account))
                .setSingleChoiceItems(items, checkedItem, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        curAddress = items[i];
                        tvAccount.setText(curAddress);
                        dialogInterface.dismiss();
                    }
                })
                .setNegativeButton(R.string.common_text_cancel, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialogInterface.dismiss();
                    }
                })
                .setCancelable(false);
        AlertDialog dialog = builder.create();
        dialog.show();
    }

    //显示转账确认界面
    private void showTransferConfirm() {
        if (curAccount == null) {
            ToastUtils.showShort(R.string.open_planet_account_exception);
            return;
        }
        if (curAccount.getAccountType() == Account.ACCOUNT_TYPE_OBSERVE) {
            ToastUtils.showShort(R.string.open_planet_observe_account_not_allowed);
            return;
        }
        //取出gas值
        String gas = blockFeeSekbar.getProgressGas();
        //显示使用
        String convertGas = blockFeeSekbar.getGasConversion();


        BottomTransferConfirmDialogFragment bottomTransferConfirmDialogFragment = new
                BottomTransferConfirmDialogFragment();

        bottomTransferConfirmDialogFragment.setData(this, ipaChainId,
                etAmount.getText().toString(), etNote.getText().toString(),
                etReceive.getText().toString(), curAddress, curWalletName,
                gas, convertGas,assetListBean, curAccount.getAccountType());
        bottomTransferConfirmDialogFragment.setStyle(STYLE_NO_FRAME, 0);
        bottomTransferConfirmDialogFragment.show(getSupportFragmentManager(), "TransferConfirm");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        if (btcTransactionManager != null) {
            btcTransactionManager.removeOnSyncListener(this);
        }
    }
}
